<template>
  <div>
    <el-dialog
      :title="info.openType == 'edit' ? '修改分类' : '添加分类'"
      :visible.sync="info.dialogVisible"
      width="50%"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="上级分类" prop="pid">
          <el-select v-model="ruleForm.pid">
            <el-option label="顶级分类" :value="0"></el-option>
            <el-option
              v-for="(item, index) in cateList"
              :key="index"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="catename" label="分类名称">
          <el-input placeholder="请输入分类名称" v-model="ruleForm.catename">
          </el-input>
        </el-form-item>
        <el-form-item prop="img" label="分类图片">
          <!-- action:上传地址 -->
          <!-- auto-upload：自动上传，默认开启，关闭这个选项 -->
          <!-- limit:图片数量限制 -->
          <!-- on-exceed:图片数量超出限制时的提示 -->
          <!-- file-list：之前上传的历史文件列表 -->
          <!-- handleChange: 上传图片成功或失败时调用的函数 -->
          <!-- handleRemove: 删除图片时调用的函数 -->
          <el-upload
            action="#"
            list-type="picture-card"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :on-remove="handleRemove"
            :on-change="handleChange"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button
            v-if="info.openType === 'edit'"
            type="primary"
            class="btn1"
            @click="submitForm"
            >立即修改</el-button
          >
          <el-button v-else type="warning" class="btn1" @click="submitForm"
            >立即添加</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getCateListFn, cateAddFn, cateEditFn } from "../../request";
export default {
  props: ["info"],
  data() {
    return {
      // 对话框是否显示
      dialogVisible: false,
      // 上级分类的下拉框
      cateList: [],
      // 历史记录的图片
      fileList: [],
      ruleForm: {
        catename: "",
        img: "",
        pid: 0,
        status: 1,
      },
      rules: {
        catename: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
        pid: [{ required: true, message: "请选择上级分类", trigger: "blur" }],
      },
      // 树形控件的数据
      treeData: [],
      // 树形控件的配置
      defaultProps: {
        children: "children",
        label: "title",
      },
    };
  },
  created() {
    // 获取下拉框的数据
    this.getCateList();
  },
  methods: {
    handleRemove(file, fileList) {
      if(file.status === "success"){
        this.ruleForm.img = '';
      }
    },
    handleExceed() {
      this.$message.warning(`当前限制选择1个文件！`);
    },
    // 上传文件时的函数
    handleChange(file, fileList) {
      // file.raw才是真正的文件
      this.ruleForm.img = file.raw;
    },
    async getCateList() {
      // 发请求获取分类列表
      this.cateList = await getCateListFn();
    },
    // 设置弹窗中的值
    setStatus(data) {
      this.ruleForm = data;
      // 清空数组
      this.fileList = [];
      // 如果有图片的数据，就修改fileList
      if (data.img) {
        this.fileList.push({
          // 固定格式，由element ui确定
          name: "pic",
          url: this.$HOST + data.img,
        });
      }
    },
    // 提交表单
    submitForm() {
      // this.$refs.ruleForm  选择表单，目的是为了校验表单
      // validate  element自带的方法，用来校验
      this.$refs.ruleForm.validate(async (valid) => {
        // valid为真时表示校验否过
        if (valid) {
          // 删除一级分类的children，这个数据不能提交
          this.ruleForm.children ? delete this.ruleForm.children : "";
          // 只要提交的数据中包含图片。无论添加还是修改。都要用FormData，将fd传给后台
          let fd = new FormData();
          // 遍历，将ruleForm的数据赋值给fd
          for (const key in this.ruleForm) {
            fd.append(key, this.ruleForm[key]);
          }
          // fd.forEach((val,key) => {
          //   console.log(key,val);
          // })
          var res;
          if (this.info.openType === "edit") {
            // edit,是修改
            res = await cateEditFn(fd);
          } else {
            // add，是新增
            res = await cateAddFn(fd);
          }
          if (res === "操作成功") {
            // 关闭弹窗
            this.$emit("close");
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>